package com.nio.c5_网络编程.serverAndclient;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @version No one is coming, unless you change yourself!!!
 * @author： pang-yun
 * @date： 2021-05-31 17:06
 */

@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        //使用nio 来理解阻塞模式
        //0.创建ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(32);

        //1.创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();

        //2. 绑定监听接口
        ssc.bind(new InetSocketAddress(9999));

        //3. 连接集合   (ssc.accept 是监听接口之后  接收来自客户端的请求)
        List<SocketChannel> channelList = new ArrayList<>();

        while (true) {
            //单个连接，有多个连接时，让ssc能够多次连接，需要用=while
            //  4. accept用来建立连接，SocketChannel用来与客户端通信
            log.debug("connecting........");
            SocketChannel socketChannel = ssc.accept();//阻塞方法，没有客户端连接时，线程停止运行
            log.debug("connected....{}",socketChannel);

            channelList.add(socketChannel);

            for (SocketChannel channel :
                    channelList) {
                // 5.接受客户端发送的数据
                log.debug("before read...{}",channel);
                channel.read(byteBuffer);  //阻塞方法， 线程停止运行  等待client端 数据
                byteBuffer.flip();
                while (byteBuffer.hasRemaining()){
                    byte b = byteBuffer.get();
                    System.out.println((char)b);
                }

                byteBuffer.clear();

                log.debug("after read...{}",channel);

            }
        }
    }
}
